﻿using System.Threading.Tasks;
using LiSAClient.LiSAService;
using LiSAClient.ServiceProvider;
using LiSAClient.WpfClient.ViewModel.Users;

namespace LiSAClient.WpfClient.ViewModel.Frame
{
    using System;
    using System.Windows.Controls;
    using System.Windows.Input;
    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;
    using LiSAClient.Core.Messages;
    using LiSAClient.Core.Models;
    using LiSAClient.Core.Services;
    using LiSAClient.Core.Services.Factories;
    using LiSAClient.Core.Viewmodel;
    using LiSAClient.WpfClient.Properties;

    internal class LoginViewModel : ContentViewModel
    {
        #region Initializers
        internal LoginViewModel()
        {
            this.Login = new RelayCommand<PasswordBox>(this.DoLogin);
            this.NewUser = new RelayCommand(this.DoNewUser);
            this.LoginEnabled = false;
            if (UserSettings.Default.IsPasswordSetToSave)
            {
                this.Username = UserSettings.Default.UserName;
                this.Password = UserSettings.Default.PassWord;
                this.IsSaveDataChecked = true;
            }
        }

        /// <summary>
        /// Set default credentials so we can communciate with the server
        /// </summary>
        public override void OnPresented()
        {
            ServiceHandler.Instance.SetCredentials("UserCreater","1234");
        }
        #endregion

        #region Observable Objects
        public ICommand Login { get; private set; }

        public ICommand NewUser { get; private set; }
        private string password;

        public string Password
        {
            get
            {
                return this.password;
            }

            set
            {
                this.Set(() => this.Password, ref this.password, value);
            }
        }

        private string username;

        public string Username
        {
            get
            {
                return this.username;
            }

            set
            {
                this.Set(() => this.Username, ref this.username, value);
                this.LoginEnabled = !string.IsNullOrEmpty(value);
            }
        }

        private bool loginEnabled;

        public bool LoginEnabled
        {
            get
            {
                return this.loginEnabled;
            }

            private set
            {
                this.Set(() => this.LoginEnabled, ref this.loginEnabled, value);
            }
        }

        private string error;

        public string Error
        {
            get
            {
                return this.error;
            }

            private set
            {
                this.Set(() => this.Error, ref this.error, value);
            }
        }

        private bool isSaveDataChecked;

        public bool IsSaveDataChecked
        {
            get
            {
                return this.isSaveDataChecked;
            }

            set
            {
                this.Set(() => this.IsSaveDataChecked, ref this.isSaveDataChecked, value);
            }
        }
        #endregion

        #region Methods
        /// <summary>
        /// This will be the only case where a visual object is given as an argument to a command.
        /// </summary>
        /// <param name="passwordBox">Password Box</param>
        private void DoLogin(PasswordBox passwordBox)
        {
            if (this.IsSaveDataChecked)
            {
                UserSettings.Default.UserName = Username;
                UserSettings.Default.PassWord = this.Password;
                UserSettings.Default.IsPasswordSetToSave = true;
            }
            else
            {
                UserSettings.Default.UserName = string.Empty;
                UserSettings.Default.PassWord = string.Empty;
                UserSettings.Default.IsPasswordSetToSave = false;
            }

            if (passwordBox == null)
            {
                throw new ArgumentNullException();
            }

            this.Presenter.StartWaiting("Logging in");
            Messenger.Default.Register<LoginCompletedMessage>(this, this.LoginSuccess);
            Messenger.Default.Register<LoginFailedMessage>(this, this.LoginFailed);
            ServiceFactory.Instance.Get<LoginService>().Login(this.username, passwordBox.SecurePassword);
        }

        private void DoNewUser()
        {
            Task.Factory.StartNew(() => this.Presenter.PresentContent(new NewUserViewModel { ShowInWindow = true }));
        }

        private void DoInfoPopup()
        {
            Messenger.Default.Send(new ShowNotificationMessage
            {
                Header = "Header text",
                Body = "Body text",
                NotificationType = NotificationType.Info
            });
        }
        #endregion

        #region Data
        #endregion

        public void LoginSuccess(LoginCompletedMessage message)
        {
            // Save stuff if checkbox is enabled
            if (IsSaveDataChecked)
            {
                UserSettings.Default.UserName = this.Username;
                UserSettings.Default.PassWord = this.Password;
                UserSettings.Default.IsPasswordSetToSave = true;
                UserSettings.Default.Save();
            }

            Messenger.Default.Unregister<LoginCompletedMessage>(this);
        }

        public void LoginFailed(LoginFailedMessage message)
        {
            Messenger.Default.Unregister<LoginFailedMessage>(this);
            this.Error = message.FailMessage;
            this.Presenter.FinishedWaiting();
        }
    }
}
